package com.sky.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.sky.annotation.ZhtTest;
import com.sky.domain.FileVo;
import com.sky.domain.Student;
import com.sky.service.StudentService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;


@RestController
@Slf4j
@RequestMapping("/sky")
public class SkyController {

    @Resource
    StudentService studentService;



    @GetMapping("/hi/{ids}")
    public List<Student> HelloWorld(@PathVariable List<Long> ids){
        ArrayList<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);
        list.add(3);

        String string = list.toString();
        System.out.println(string);
        System.out.println("=======================================");

        System.out.println(LocalDate.now());
        LocalDate now = LocalDate.now();
        String replace = now.toString().replace("-", "");
        System.out.println(replace);
        //拼接查询表名
        String tableName = "student_" + now.getYear() + "_" + now.getMonthValue();
        List<Student> studentList = studentService.selectByIds(ids,tableName);
        System.out.println("=======================================");
//        for (Student student : studentList) {
//            if(StringUtils.isNotEmpty(student.getFile())){
//                String file = student.getFile();
//                JSONArray jsonArray = JSONArray.parseArray(file);
//                List<FileVo> studentList1 = jsonArray.toJavaList(FileVo.class);
//
//                System.out.println(studentList1);
//            }
//        }

        System.out.println("=========================================================");


        System.out.println(studentList);
        return studentList;
    }

    @PostMapping("/insert")
    public void insert(@RequestBody Student student){
        List<Long> ids = new ArrayList<>();
        ids.add(1L);
        ids.add(2L);
        LocalDate now = LocalDate.now();

        String tableName = "student_" + now.getYear() + "_" + now.getMonthValue();
        List<Student> studentList = studentService.selectByIds(ids ,tableName);


        List<Long> longs = new ArrayList<>();
        longs.add(31L);
        longs.add(654L);
        longs.add(6544L);

        for (int i = 0; i < longs.size() ; i++) {
            if (i==1){
                longs.remove(i);
            }
            System.out.println(longs.get(i));
        }

        for (int i = longs.size() -1; i > 0 ; i--) {
            if (i==1){
                longs.remove(i);
                i--;
            }
            System.out.println(longs.get(i));
        }



        if(studentList.contains(1l)){
            System.out.println("1213213132132=========================================");
        }

        StringBuilder stringBuilder = new StringBuilder();

        for (Student student1 : studentList) {
            if(StringUtils.isNotEmpty(student1.getFile())){
                JSONArray array = JSONArray.parseArray(student1.getFile());
                List<FileVo> fileVos = array.toJavaList(FileVo.class);
                FileVo fileVo = new FileVo();
                fileVo.setName(student.getName());
                fileVo.setUrl("null");
                fileVo.setPerpetual(false);
                fileVo.setType(5);
                fileVo.setSize(5);
                fileVos.add(fileVo);
                for (FileVo vo : fileVos) {
                    stringBuilder = stringBuilder.append(JSON.toJSON(vo) + ",");
                }
                stringBuilder.deleteCharAt(stringBuilder.length()-1);
                stringBuilder.insert(0,"[").insert(stringBuilder.length(),"]");


            }
        }

        student.setFile(stringBuilder.toString());
        int determine = studentService.insert(student);
        String result = determine > 0 ? "插入成功!":"插入失败";
        System.out.println("=====================================================================");

        System.out.println(LocalDate.now());

        log.info(result);
    }

    @DeleteMapping("/delete/{id}")
    public void deleteById(@PathVariable Long id){
        int determine = studentService.deleteById(id);
        String result = determine > 0 ? "删除成功!":"删除失败";
        log.info(result);
    }

    @GetMapping
    public void GDTest(){
        Map<String,Student> map = studentService.getMap();
        System.out.println(map.get("李四").getAge());
    }

    @GetMapping("/import")
    public void GDImport(){
        studentService.importList();
    }

    @GetMapping("/test")
    public void test(){


        System.out.println();


        String time = LocalDate.now().plusDays(-1).toString().replace("-", "");

        List<Student> studentList = new ArrayList<>();
        Student student = new Student();
        student.setName("张三");
        student.setAge(3);
        studentList.add(student);
        Student student1 = new Student();
        student1.setName("李四");
        student1.setAge(6);
        studentList.add(student1);
        Student student2 = new Student();
        student2.setName("王五");
        student2.setAge(16);
        studentList.add(student2);

        List<String> studentNameList = new ArrayList<>();
        studentNameList.add("张三");
        studentNameList.add("赵六");
        studentNameList.add("sky");

        for (int i = studentList.size() - 1; i >= 0; i--) {
            for (String ownerManagement : studentNameList) {
                if (studentList.get(i).getName().equals(ownerManagement)) {
                    studentList.remove(i);
                    i--;
                }
            }
        }
//        studentList.removeIf(s1 -> studentNameList.stream().anyMatch(s2 -> s2.equals(s1.getName())));
        studentList.stream().filter(s1->studentNameList.stream().anyMatch(s2->s2.equals(s1.getName())))
                .forEach(it->it.setName(it.getName()+"1"));
        List<Student> collect = studentList.stream().filter(s -> s.getName() != null).collect(Collectors.toList());
        System.out.println(collect);


    }

    @GetMapping("/test1")
    public void test1() throws InterruptedException {

        ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(4  , 8, 5, TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(100000), new ThreadPoolExecutor.AbortPolicy());

        CountDownLatch latch = new CountDownLatch(10);
        //线程异执行
        for(int i = 0; i<10;i++){
            CompletableFuture.supplyAsync(this::test1_1,poolExecutor
            ).thenAccept(dto -> {//获取返回结果
                System.out.println(dto);
                latch.countDown();
            });
        }
        latch.await(5,TimeUnit.SECONDS);
        System.out.println("---------------------------------------------------------------------------");


//        try {
//            latch.await(300, TimeUnit.SECONDS);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
    }


    volatile int num = 0;
    public synchronized String test1_1(){
        ReentrantLock reentrantLock = new ReentrantLock();
        num++;
        return Thread.currentThread().getName() + ":" + System.currentTimeMillis() + "-" +num;
    }


    @GetMapping("/redisTest")
    public void redisTest() {
        studentService.setKey("SKY_TEST", "sky");
    }

    @GetMapping("/testInterceptor")
    @ZhtTest(text = "拦截器测试")
    public void testInterceptor() {
        System.out.println("哈哈");
    }

    @GetMapping("/AOPTest")
    public void AOPTest() {
        studentService.AOPTest();
    }
}
